import api from '../utils/Common'

const messageSeparator = '2sep1'
const JOIN_GAME = 0
const JOIN_SUCCESS = -1
const JOIN_FAILED = -2
const GET_CARD = 1
const SHOW_CARD = 2
const CARD_COMPARE = 3
const SHOW_MESSAGE = 88
const GAME_OVER = 89
const UPDATE_DATA = 99
const RESET_GAME = 100
const START_GAME = 1000
const CHECK = 1001
const LOOK_CARDS = 1002
const GIVE_UP = 1003
const BATTLE = 1004

function initSocket (showMessage, socketName) {
  // 判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    let webSocket = new WebSocket(api.socketUrl + socketName)
    // 连接发生错误的回调方法
    webSocket.onerror = function () {
      showMessage('error')
    }

    // 连接成功建立的回调方法
    webSocket.onopen = function (event) {
      showMessage('连接成功,请加入游戏')
    }

    // 连接关闭的回调方法
    webSocket.onclose = function () {
      showMessage('连接断开了')
    }

    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
      webSocket.close()
    }
    return webSocket
  } else {
    alert('Not support webSocket')
  }
}

export default {
  initSocket,
  messageSeparator,
  JOIN_GAME,
  JOIN_SUCCESS,
  JOIN_FAILED,
  GET_CARD,
  SHOW_CARD,
  CARD_COMPARE,
  SHOW_MESSAGE,
  UPDATE_DATA,
  RESET_GAME,
  GAME_OVER,

  START_GAME,
  CHECK,
  LOOK_CARDS,
  GIVE_UP,
  BATTLE
}
